<template>
  <a-form-item-rest>
    <div>
      <a-date-picker v-model:value="datePickerValue" v-bind="$attrs" :locale="locale" @change="handleChange" />
      <a-select
        style="width: 100px; margin-left: 4px"
        v-model:value="selectValue"
        v-bind="$attrs"
        :options="[
          { label: '上午', value: 'am' },
          { label: '下午', value: 'pm' },
        ]"
        @change="handleChange"
      />
    </div>
  </a-form-item-rest>
</template>

<script>
  import { defineComponent, ref, watch } from 'vue';
  import { Form } from 'ant-design-vue';
  import locale from 'ant-design-vue/es/date-picker/locale/zh_CN';
  import dayjs from 'dayjs';
  import 'dayjs/locale/zh-cn';

  dayjs.locale('zh-cn');
  /**
   * 用于时间-time组件的范围查询
   */
  export default defineComponent({
    name: 'JDatePicker',
    props: {
      value: {
        type: [Array], // ['2023-01-01', 'am']、['2023-01-01', 'pm']
      },
    },
    emits: ['change', 'update:value'],
    setup(props, { emit }) {
      const datePickerValue = ref();
      const selectValue = ref();
      const formItemContext = Form.useInjectFormItemContext();

      watch(
        () => props.value,
        () => {
          if (Array.isArray(props.value) && props.value.length == 2) {
            if (props.value[0]) {
              datePickerValue.value = dayjs(props.value[0], 'YYYY-MM-DD');
            }
            if (props.value[1]) {
              selectValue.value = props.value[1];
            }
          }
        },
        {
          immediate: true,
        }
      );

      function handleChange(arr) {
        //console.log('wang-handle', arr, datePickerValue.value, selectValue.value);
        if (datePickerValue.value) {
          emit('update:value', [dayjs(datePickerValue.value).format('YYYY-MM-DD'), selectValue.value]);
          emit('change', [dayjs(datePickerValue.value).format('YYYY-MM-DD'), selectValue.value]);
        } else {
          emit('change', [null, selectValue.value]);
          emit('update:value', [undefined, selectValue.value]);
        }
        formItemContext.onFieldChange();
      }

      return {
        locale,
        datePickerValue,
        selectValue,
        handleChange,
      };
    },
  });
</script>
